<?php
require_once("inc.public.php");

$this_title=__($vars["title"])." &raquo; ".__("Registration");
$page_title=replace_tag(__("<%title%> &raquo; Registration"), array("<%title%>"=>__($vars["title"])));
$content_title=__("Register");
$terms_file=$vars["file"]["public"]["terms"];

//referrer cookie
if($cookie_s["r"]){
 $uid=@mysql_result(mysql_query("select id from $db->users where id='$cookie_d[r]' and status='normal' limit 1"), 0) or "";
 if($uid){
  setcookie("r", $uid, time()+$vars["referral_cookie_duration"]*86400, "/");
  $cookie_ref=$uid;
 }
}

$r_bc=array('1','3','7','15');
$r_bc_d=array('1'=>'1','3'=>'3','7'=>'7','15'=>'15');
$r_gender=array("m", "f");
$r_gender_d=array("m"=>__("Male"), "f"=>__("Female"));
$country_code=$vars['common']['country_code'];
array_shift($country_code);
$country_code_t=$vars['common']['country_code_text'];
foreach($country_code_t as $code=>$cname){
 $country_code_d[$code]=__($cname);
}

$td_width=175;

//#####AJAX CALL#####
if($_GET["aj"] && $_GET["check_ref"]){
 if(!$r_ref=@mysql_fetch_assoc(mysql_query("select * from $db->users where id='$post_d[ref]' and status in ('suspended','normal') and primary_acc='y'"))){
  $ajerrmsg=replace_tag(__("Sponsor ID '<%id%>' could not be found."), array("<%id%>"=>$post_h['ref']));
 }else{
  $ajmsg=replace_tag(__("Sponsor ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$post_h['ref'], "<%name%>"=>$r_ref['name']));
 }
 $xml=array("status"=>($ajerrmsg? "2" : "1"), "msg"=>$ajmsg.$ajerrmsg);
 print format_xml($xml);
 exit();
}
//#####END AJAX CALL#####

//#####REGISTER POST#####
if($_SESSION["user_register"] && $_POST["__req"]){
	/*##### ERROR CHECK #####*/
	$chk_arr="_username,_name,_password,_email,_address,_address2,_city,_zip,_state,_mobileno,_officeno,_faxno,_bank_name,_bank_acc_no";
	if($post_s["acc_type"]=="p"){
		$chk_arr.=",_ic,_homeno,_occupation";
	}else{
		$chk_arr.=",_bis_reg,_person_in_charge";
	}
	$chk_arr=explode(",", $chk_arr);
	foreach($post_s as $f=>$v){
		if(in_array($f, $chk_arr)){
			$data[$f]=$v;
		}
	}
	$errmsg=verify_form_data("users", $data);
	if(!$errmsg){
		//check referrer
		if($post_s["ref"]){
			if(!$r_ref=@mysql_fetch_assoc(mysql_query("select * from $db->users where id='$post_d[ref]' and status in ('suspended','normal') and primary_acc='y'"))){
				$errmsg.=replace_tag(__("Sponsor ID: '<%rid%>' cannot be found in the database."), array("<%rid%>"=>$post_h['ref']))."<br />\n";
			}else{
				$ref_found=1;
				$ref_id=$r_ref["id"];
			}
		}else{
			$ref_id=0;
		}
		if($post_s["acc_type"]=="p"){
			//check ic
			if(ic_found($post_d["_ic"])){
				$errmsg.=replace_tag(__("I/C No. '<%ic%>' belongs to another member."), array("<%ic%>"=>$post_h['_ic']))."<br />\n";
			}
			//check dob
			$dob="$post_s[dob_year]-".pad_length($post_s["dob_month"], 2)."-".pad_length($post_s["dob_day"], 2);
			if(!@checkdate($post_s["dob_month"], $post_s["dob_day"], $post_s["dob_year"])){
				$errmsg=__("Invalid date format selected for DOB.")."<br />\n";
			}
			//check gender
			if(!in_array($post_s["gender"], $r_gender)){
				$errmsg.=__("Please specify Gender.")."<br />\n";
			}
		}elseif($post_s["acc_type"]=="c"){
			//check business reg no
			if(bis_reg_found($post_d["_bis_reg"])){
				$errmsg.=replace_tag(__("Company Reg. No. '<%bis_reg%>' belongs to another member."), array("<%bis_reg%>"=>$post_h['_ic']))."<br />\n";
			}
		}
		//check username
		if(preg_match('/[^a-zA-Z0-9_]+/', $post_s["_username"])){
			$errmsg.=replace_tag(__("Username can only accept a to z, A to Z, numbers (0 - 9), and underscore (_) only, you have provided '<%username%>'. Please provide a valid username."), array("<%username%>"=>$post_h["_username"]))."<br />\n";
		}elseif(username_found($post_d["_username"])){
			$errmsg.=replace_tag(__("The username '<%username%>' is not available, please choose another."), array("<%username%>"=>$post_h["_username"]))."<br />\n";
		}
		//check password
		if(!is_alphanum($post_s["_password"])){
			$errmsg.=replace_tag(__("'<%field%>' must be a combination of numbers and alphabets."), array("<%field%>"=>__("Password")))."<br />\n";
		}elseif($post_s["_password"] != $post_s["password2"]){
			$errmsg.=__("Your entered passwords did not match.")."<br />\n";
		}
		//check email
		if(!verify_email($post_s["_email"])){
			$errmsg.=__("Please provide a valid email address.")."<br />\n";
		}elseif(email_found($post_d["_email"])){
			$errmsg.=replace_tag(__("The email address '<%email%>' is already in use. Please provide another."), array("<%email%>"=>$post_h['_email']))."<br />\n";
		}
		//check BC
		if(!in_array($post_s['bc'], $r_bc)){
			$errmsg.=__("Please specify the number of BC that you wish to purchase.")."<br />";
		}
		//check terms
		if(!$post_s["terms"]){
			$errmsg.=replace_tag(__("You must agree to the Terms of Service of <%title%>."), array("<%title%>"=>__($vars["title"])))."<br />\n";
		}
	}
	//#####END ERROR CHECK#####

	//#####ADD TO DB#####
	if(!$errmsg){
		$field_arr=$chk_arr;
		for($i=0,$t=count($field_arr);$i<$t;$i++){
			$ufq.=($ufq? ", " : "").(substr($field_arr[$i], 0, 1) == '_'? substr($field_arr[$i], 1) : $field_arr[$i]);
			$uvq.=($uvq? ", " : "")."'".$post_d[$field_arr[$i]]."'";
		}
		if($post_s["acc_type"]=="p"){
			$ufq.=", dob, gender";
			$uvq.=", '$dob', '$post_d[gender]'";
		}
		$salt=generate_random_code(32);
		$enc_pass=md5($post_s["_password"].$salt).":".$salt;
		$status='normal';
		$activated='n';
		$vc=generate_random_code(20);
		$datetime=ndate($vars["system_date_format"]);
		$sql="insert into $db->users (acc_type, ref, primary_acc, $ufq, enc_password, country, status, activated, cdate)
		values ('$post_d[acc_type]', '$ref_id', 'y', $uvq, '$enc_pass', '$post_d[country]', '$status', '$activated', '$datetime')";
		if(!mysql_query($sql)){
			$errmsg.=__("We have encountered some error and the registration process has been failed.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
		}else{
			$new_uid=mysql_insert_id();
			$activation_link="<a href='".M_URL."/$activation_file?vc=$vc&email=$post_s[_email]'>".M_URL."/$activation_file?vc=$vc&email=$post_s[_email]</a>";
			
			//create multiple BC
			if($post_s['bc'] > 1){
				$next_i = 2;
				for($i=1;$i<$post_s['bc'];$i++){
					if($i <= 2){
						$sponsor = $new_uid;
						$matrix_upline = $new_uid;
						$matrix_position = $i;
					}elseif($i <= 4){
						$sponsor = $matrix_id[1];
						$matrix_upline = $matrix_id[1];
						$matrix_position = $i - 2;
					}elseif($i <= 6){
						$sponsor = $matrix_id[2];
						$matrix_upline = $matrix_id[2];
						$matrix_position = $i - 4;
					}elseif($i <= 8){
						$sponsor = $matrix_id[3];
						$matrix_upline = $matrix_id[3];
						$matrix_position = $i - 6;
					}elseif($i <= 10){
						$sponsor = $matrix_id[4];
						$matrix_upline = $matrix_id[4];
						$matrix_position = $i - 8;
					}elseif($i <= 12){
						$sponsor = $matrix_id[5];
						$matrix_upline = $matrix_id[5];
						$matrix_position = $i - 10;
					}elseif($i <= 14){
						$sponsor = $matrix_id[6];
						$matrix_upline = $matrix_id[6];
						$matrix_position = $i - 12;
					}
					do{
						$next_username = $post_d['_username'].$next_i;
						$next_i++;
					}while(username_found($next_username));
					$sql="insert into $db->users (primary_acc, primary_id, ref, username, matrix_upline, matrix_position, status, activated, cdate) values ('n', '$new_uid', '$sponsor', '$next_username', '$matrix_upline', '$matrix_position', '$status', '$activated', '$datetime')";
					if(!mysql_query($sql)){
						$bc_errmsg.=replace_tag(__("Error creating the sub-account for account no. <%x%>."), array("<%x%>"=>strval($i+1)))."<br />".($vars['debug']? "<br />SQL: $sql<br /><br />Error: ".mysql_error()."<br />" : "");
					}else{
						$matrix_id[$i] = mysql_insert_id();
					}
				}
			}
			
			//email user
			$msg_style=$vars["css"]["msg_style"];
			$td_style=$vars["css"]["td_style"];
			$td_title_style=$vars["css"]["td_title_style"];
			$u_sub="$vars[title] - Thank You for Your Registration";
			$user_table="
			<table align='center' ".$vars["css"]["table_style"]." width='100%'>
			<tr>
			<td $td_title_style colspan='2'>Account Information</td>
			</tr>
			<tr>
			<td $td_style width='120'>User ID</td>
			<td $td_style>$new_uid</td>
			</tr>
			<tr>
			<td $td_style>Sponsor</td>
			<td $td_style>".($ref_id? "$r_ref[name] (ID: $post_s[ref])" : "None")."</td>
			</tr>
			<tr>
			<td $td_style>Username</td>
			<td $td_style>$post_s[_username]</td>
			</tr>
			<tr>
			<td $td_style>Password</td>
			<td $td_style>$post_s[_password]</td>
			</tr>
			<tr>
			<td $td_title_style colspan='2'>User Information</td>
			</tr>
			<tr>
			<td $td_style width='120'>".($post_s["acc_type"]=="c"? "Company" : "")." Name</td>
			<td $td_style>$post_s[_name]</td>
			</tr>
			<tr>
			<td $td_style>".($post_s["acc_type"]=="c"? "Company Reg. No." : "IC No.")."</td>
			<td $td_style>".($post_s["acc_type"]=="c"? $post_s["_bis_reg"] : $post_s["_ic"])."</td>
			</tr>".($post_s["acc_type"]=="p"? "
			<tr>
			<td $td_style>Gender</td>
			<td $td_style>".$r_gender_d[$post_s["gender"]]."</td>
			</tr>" : "")."
			<tr>
			<td $td_style>Country</td>
			<td $td_style>".$country_code_d[$post_s["country"]]."</td>
			</tr>
			<tr>
			<td $td_style>Mobile No.</td>
			<td $td_style>$post_s[_mobileno]</td>
			</tr>".($post_s["acc_type"]=="c"? "
			<tr>
			<td $td_style>Telephone No.</td>
			<td $td_style>$post_s[_officeno]</td>
			</tr>
			<tr>
			<td $td_style>Fax No.</td>
			<td $td_style>$post_s[_faxno]</td>
			</tr>" : "")."
			<tr>
			<td $td_style>Email</td>
			<td $td_style>$post_s[_email]</td>
			</tr>
			<tr>
			<td $td_style>Number of BC</td>
			<td $td_style>$post_s[bc]</td>
			</tr>
			</table>";
			$u_msg=
			"<p $msg_style>Dear $post_s[_name], <br />\n<br />\nThank you for your registration. The user information for your new account is listed below:</p>
			$user_table";
			if(email_user($post_s["_email"], $u_sub, $u_msg)){
				$email_msg=replace_tag(__("A welcome email has been sent to '<%email%>'."), array("<%email%>"=>$post_h['_email']));
			}else{
				$email_errmsg=replace_tag(__("The Welcome email could not be sent to '<%email%>', please contact us for more information."), array("<%email%>"=>$post_h['_email']));
			}

			//email referrer
			if($post_s["ref"]){
				$r_sub=$vars["title"]." - You have just sponsored a new member in your downline group!";
				$r_msg=
				"<p>Dear $r_ref[name],</p>
				<p>Congratulations! You have just sponsored a new member in your downline group. The member details of your new downline are as below:</p>
				<p>Downline ID: $new_uid<br />\nName: $post_s[_name]<br />\nEmail: $post_s[_email]</p>
				<p>You can check your network <a href='".M_URL."/members/".$vars["file"]["member"]["genealogy"]."'>here</a>. Keep up the good work!</p>";
				email_user($r_ref["email"], $r_sub, $r_msg);
			}
		}
		if(!$errmsg){
			$_SESSION["user_register"]=false;
			$msg=__("Thank you for your registration.")." ".
			($email_msg? $email_msg : "<span class='red'>$email_errmsg</span>")."<br />\n".
			($bc_errmsg? "<br /><br /><span class='red'>$bc_errmsg<br /><br />Please contact us.</span>" : "");
			print format_public_page("<h2>$page_title</h2>".format_msg($msg)."<p>".__("The user information of your account is listed below:")."</p>$user_table", $this_title, $content_title);
			exit();
		}
	}

	$errmsg=$errmsg? format_err($errmsg) : "";
}
$_SESSION["user_register"]=true;

$form_fields=array("acc_type"=>"p","ref"=>$cookie_ref,"_person_in_charge"=>"","_bis_reg"=>"","_username"=>"","_name"=>"","_password"=>"","password2"=>"","_email"=>"","_ic"=>"","_address"=>"","_address2"=>"","_city"=>"","_zip"=>"","_state"=>"","country"=>"MY","_homeno"=>"","_mobileno"=>"","_officeno"=>"","_faxno"=>"","dob_day"=>"","dob_month"=>"","dob_year"=>"","gender"=>"m","_occupation"=>"","_bank_name"=>"","_bank_acc_no"=>"","bc"=>'1', "terms"=>"");
foreach($form_fields as $field => $default){
 $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
 $dis[$field]=!$posting? $default : $post_h[$field];
}

$country_select=build_select($country_code, $country_code_d, $dis["country"], "country", $inputbox_style);
$gender_select=build_select($r_gender, $r_gender_d, $dis["gender"], "gender", $inputbox_style);
$dob_input=generate_dmy_input("dob", $dis["dob_day"], $dis["dob_month"], $dis["dob_year"], "class='inputbox'");
$bc_select=build_select($r_bc, $r_bc_d, $dis["bc"], "bc", $inputbox_style);

//referrer
if($dis["ref"]){
 if($r=get_user_detail_by_id($dis["ref"])){
  $ref_text="<span class='bold'>".replace_tag(__("Sponsor ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$dis['ref'], "<%name%>"=>$r["name"]))."</span>";
 }else{
  $ref_text="<span class='red'>".__("Invalid Sponsor")."</span>";
 }
}

//javascript
$jvscript=
"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("common.js,jquery.js")."'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
 j('form[@name=member_form]').submit(function(){
  j('input[@name=submit_btn]').attr('disabled','disabled');
 });

 j('input#check_ref_btn').click(function(){
  j('span#ref_text').html('').removeClass('red');
  if(j('input[@name=ref]').val()==''){
   j('span#ref_text').html('".AddSlashes(__("Please provide a Sponsor ID!"))."').addClass('red');
  }else{
   j('span#ref_text').html('Checking...');
   j(this).attr('disabled','disabled');
   j.ajax({
    url: '$this_file?aj=1&check_ref=1',
    data: {'ref': j('input[@name=ref]').val()},
    type: 'post',
    dataType: 'xml',
    error: function(){
     j('span#ref_text').html('".AddSlashes(__("Error checking..."))."').addClass('red');
    },
    success: function(data){
     var mesg='';
     if(j('loggedout', data).text()=='loggedout'){
      mesg='".AddSlashes(__("You have been logged out."))."';
     }else{
      j(data).find('msg').each(function(){
       mesg+=j(this).text()+' ';
      });
     }
     var status=j(data).find('status').text();
     j('span#ref_text').html(mesg).addClass(status==1? 'bold' : 'red');
    },
    complete: function(){
     j('input#check_ref_btn').attr('disabled','');
    }
   });
  }
 });
});

function update_acc_type(type){
 if(type=='p'){
  personal_d='block';
  company_d='none';
 }else{
  personal_d='none';
  company_d='block';
 }
 q('acctype_personal').style.display=personal_d;
 q('acctype_personal_home').style.display=personal_d;
 q('acctype_company').style.display=company_d;
}
</script>";

//content jvscript
$c_jvscript=
"<script type='text/javascript'>
update_acc_type('$dis[acc_type]');
</script>";

$display_fields=array("ref","_person_in_charge","_bis_reg","_username","_name","_password","_email","_ic","_address","_address2","_city","_zip","_state","_homeno","_mobileno","_officeno","_faxno","_occupation","_bank_name","_bank_acc_no");
foreach($form_fields as $field => $default){
 if(in_array($field, $display_fields)){
  $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
  $dbr=explode("#", $vars["dbr"]["users"][$db_fieldname]);
  $readonly=$textarea=$password=false;
  if($field=='ref'){
   $extra_display="<div style='margin-top:5px;'>".__("You can provide your Sponsor ID here if you have one, or you can leave this field blank.")."
   <span id='ref_text'>$ref_text</span> <input type='button' value=\"".__("Check Sponsor")."\" id='check_ref_btn' /></div>";
  }elseif($field=='_username'){
   $extra_display="<br />\n".__("Please provide only a to z, A to Z, numbers (0 - 9), and underscore (_) for username.");
  }elseif($field=='_bank_acc_no'){
   $extra_display="<br />\n<input type='checkbox' name='terms' ".($dis["terms"]? "checked='checked'" : "")." id='chk_terms' /><label for='chk_terms'>".replace_tag(__("I have read and agreed to the <%link%>Terms of Service<%/link%> of <%title%>."), array("<%link%>"=>"<a href='".$vars["file"]["public"]["terms"]."' target='_blank'>", "<%/link%>"=>"</a>", "<%title%>"=>__($vars["title"])))."</label>";
  }else{
   $extra_display='';
  }
  if(in_array($field, array("_password","_sec_password"))){
   $password=true;
  }
  $readonly_str=$readonly? "readonly='readonly'" : "";
  $form_inputfield[$db_fieldname]="
  <tr id='input_$db_fieldname'>
   <td width='$td_width'><div style='width:".$td_width."px;'>".__($dbr[4]).__(":").($dbr[3]=='m'? " ".__("*") : "")."</div></td>
   <td>".($textarea? "<textarea name='$field' rows='6' $inputbox_style $readonly_str>".$dis[$field]."</textarea>" : "
   <input type='".($password? "password" : "text")."' name='$field' $inputbox_style value=\"".$dis[$field]."\" $readonly_str />")."$extra_display</td>
  </tr>";
 }
}


$register=($errmsg?
"$errmsg" : "")."
<form name='aj_form' method='post' action='$this_file'></form>
<form name='member_form' method='post' action='$this_file'>
<input type='hidden' name='__req' value='1' />
<table class='pbt_table'>
 <tr class='pbt_header'>
  <td colspan='2'>".__("Account Information")."</td>
 </tr>   
 <tr>
  <td>".__("Account Type").__(":")." ".__("*")."</td>
  <td><input type='radio' name='acc_type' value=\"p\" id='accp' class='no_bg' ".($dis['acc_type']=="p"? "checked='checked'" : "")." onclick='update_acc_type(this.value);' onkeydown='update_acc_type(this.value);' /><label for='accp'>".__("Personal")."</label>
      <input type='radio' name='acc_type' value=\"c\" id='accc' class='no_bg' ".($dis['acc_type']=="c"? "checked='checked'" : "")." onclick='update_acc_type(this.value);' onkeydown='update_acc_type(this.value);' /><label for='accc'>".__("Company")."</label>
  </td>
 </tr>
 $form_inputfield[ref]
 $form_inputfield[username]
 $form_inputfield[password]
 <tr>
  <td>".__("Confirm Password").__(":")." ".__("*")."</td>
  <td><input type='password' name='password2' $inputbox_style value=\"$dis[password2]\"></td>
 </tr>
 $form_inputfield[name]
 $form_inputfield[email]
</table>
<div id='acctype_personal'>
<table class='pbt_table'>
 $form_inputfield[ic]
 <tr>
  <td>".__("Gender").__(":")." ".__("*")."</td>
  <td>$gender_select</td>
 </tr>
 $form_inputfield[occupation]
 <tr>
  <td>".__("Date of Birth").__(":")." ".__("*")."</td>
  <td>$dob_input</td>
 </tr>
</table>
</div>
<div id='acctype_company'>
<table class='pbt_table'>
 $form_inputfield[bis_reg]
 $form_inputfield[person_in_charge]
</table>
</div>
<table class='pbt_table'>
 $form_inputfield[address]
 $form_inputfield[address2]
 $form_inputfield[city]
 $form_inputfield[zip]
 $form_inputfield[state]
 <tr>
  <td>".__("Country").__(":")." ".__("*")."</td>
  <td>$country_select</td>
 </tr>
</table>
<div id='acctype_personal_home'>
<table class='pbt_table'>
 $form_inputfield[homeno]
</table>
</div>
<table class='pbt_table'>
 $form_inputfield[mobileno]
 $form_inputfield[officeno]
 $form_inputfield[faxno]
 <tr>
  <td>".__("Number of BC").__(":")." ".__("*")."</td>
  <td>$bc_select<br />".__("If you purchase more than 1 BC, the 2nd BC onwards will follow the primary user information.")."</td>
 </tr>
 <tr class='pbt_header'>
  <td colspan='2'>".__("Payment Information").__(":")." ".__("*")."</td>
 </tr>
 $form_inputfield[bank_name]
 $form_inputfield[bank_acc_no]
 <tr>
  <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
   <input type='submit' name='submit_btn' value=\"".__("Register")."\" />
  </td>
 </tr>
</table>
$c_jvscript";

$content="<h2>$page_title</h2>$register";

print format_public_page($content, $this_title, $content_title, $jvscript);
?>